﻿using LitJson;
using System;
using TableCore.Exceptions;

namespace TableCore
{
    public class GenData
    {
        int _id;
        public int id
        {
            get { return _id; }
            set
            {
                _id = value;
                mData[mContent.Cmodel.IdIndex] = Localization.ToString(value);
            }
        }

        //ClassModel mMod;
        GTFile.Content mContent;
        string[] mData;
        string[] mComments;
        string[] mCells;
        JsonData mFormatData;
        bool mDirty;

        public GenData(GTFile.Content content)
        {
            mContent = content;
            mDirty = true;
            mData = new string[content.Cmodel.PropertyCount];
            mComments = new string[mData.Length];
            mCells = new string[mData.Length];
        }

        public GenData Copy(int newid)
        {
            var data = new GenData(mContent);
            if(mData.Length > 0)
                System.Array.Copy(mData, data.mData, mData.Length);
            data.id = newid;
            return data;
        }

        public void SetProperty(int index, string data, string cellName, string comment)
        {
            var pro = mContent.Cmodel.Properties[index].GenType;
            var dt = pro.FormatInput(data);
          
            if(!pro.IsValid(dt))
                throw new ValueNotMatchTypeException(mContent, data, pro, cellName);
            mData[index] = dt;
            mComments[index] = comment;
            mCells[index] = cellName;
            if (index == mContent.Cmodel.IdIndex)
            {
                //int i;
                //if (!int.TryParse(dt, out i))
                //    throw new ValueNotMatchTypeException(data, mMod.Properties[index].GenType, cell);

                _id = (int)pro.Format(mContent, dt, cellName, comment);
            }
            mDirty = true;
        }

        public string GetProperty(int index)
        {
            return mData[index];
        }
        
        public string GetProperty(string pname)
        {
            int i = mContent.Cmodel.IndexOfProperty(pname);
            if (i == -1)
                return null;
            else
                return GetProperty(i);
        }

        public JsonData GetFormatData()
        {
            if (mDirty || mFormatData == null)
            {
                mDirty = false;
                mFormatData = new JsonData();
                for (int i = 0; i < mData.Length; i++)
                {
                    var pro = mContent.Cmodel.Properties[i];
                    if (pro.Ignore)
                        continue;
                    mFormatData[pro.Name] = pro.GenType.Format(mContent, mData[i], mCells[i], mComments[i]);
                }
            }
            return mFormatData;
        }
    }
}
